//
//  CK_MenuViewController.m
//  MenuDemo
//
//  Created by 陈凯 on 16/4/14.
//  Copyright © 2016年 鸥！陈凯. All rights reserved.
//

#import "CK_MenuViewController.h"
#import <objc/message.h>
#import "LWXCollectionController.h"
#import "DoenloadTableController.h"
// 抽屉展开的程度
#define kMenuLeftWidth [UIScreen mainScreen].bounds.size.width * 0.7

@interface CK_MenuViewController ()<UITableViewDataSource, UITableViewDelegate>

// 默认左侧tableView
@property (nonatomic, strong) UITableView *leftTableView;

@property (nonatomic, assign) NSInteger index;

@end

@implementation CK_MenuViewController
// 判断当前是否展开
- (BOOL)isShowing {
    if (self.centerViewController.view.transform.tx > 0) {
        return YES;
    }
    return NO;
}
// 初始化方法
static CK_MenuViewController *CK_menuVC = nil;
+ (instancetype)instanceWithLeftViewController:(UIViewController *)leftVC CenterViewController:(UIViewController *)centerVC {
    @synchronized(self) {
        if (!CK_menuVC) {
            
            CK_menuVC = [[CK_MenuViewController alloc]init];
            // 设置window的rootViewController
            [UIApplication sharedApplication].keyWindow.rootViewController = CK_menuVC;
            // 设置属性
            CK_menuVC.leftViewController = leftVC;
            CK_menuVC.centerViewController = centerVC;
            // 添加子视图控制器和子视图
            if (leftVC) {
                [CK_menuVC addChildViewController:leftVC];
                [CK_menuVC.view addSubview:leftVC.view];
            }else {
                [CK_menuVC setupLeftViewController];
            }
            if (centerVC) {
                [CK_menuVC addChildViewController:centerVC];
                [CK_menuVC.view addSubview:centerVC.view];
            }
        }
    }
    return CK_menuVC;
}
// 默认的菜单视图
- (void)setupLeftViewController {
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, self.view.frame.size.height) style:UITableViewStylePlain];
   // self.leftTableView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"scenery.jpg"]];
    self.leftTableView.backgroundColor = [UIColor darkGrayColor];
    //取消滑动
    self.leftTableView.scrollEnabled = NO;
    //取消回弹
    self.leftTableView.bounces = NO;
    
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 设置数据源
    self.leftTableView.dataSource = self;
    // 代理
    self.leftTableView.delegate = self;
    [self.view addSubview:self.leftTableView];
}
#pragma mark - UITableViewDataSource
// 数据源代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return self.menuArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (self.view.frame.size.height - 258) / 8;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuserID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserID];
    }
    if (indexPath.row == 6) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(20, 0, kMenuLeftWidth - 40, 1)];
        view.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:view];
    }
    
    
   
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //设置选中后字体的颜色的状态
    [cell setSelectedTextColor:[UIColor whiteColor]];
    //cell.textLabel.highlightedTextColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = self.menuArray[indexPath.row];
    cell.textLabel.textColor = [UIColor lightGrayColor];
    //选中cell的颜色
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor darkGrayColor];
    cell.selectedBackgroundView = backView;
    

    
    
 return cell;

}
// menuArray的setter方法
- (void)setMenuArray:(NSMutableArray *)menuArray {
    if (_menuArray != menuArray) {
        _menuArray  = nil;
        _menuArray  = menuArray;
        [self.leftTableView reloadData];
    }
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.index = indexPath.row;
    
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 代理 传值
    
    if ([self.menuDelegate respondsToSelector:@selector(didClickMenuIndex:Title:)]) {
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray[indexPath.row]];
    }
    // 关闭抽屉
    [self hideLeftViewController];
}


#pragma mark - viewForHeader

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 170;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kMenuLeftWidth, 170)];
    //添加分割线
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, 64, kMenuLeftWidth - 40, 2)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [headView addSubview:lineView];
   //添加分割线
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(20, 168, kMenuLeftWidth - 40, 1)];
    lineView1.backgroundColor = [UIColor lightGrayColor];
    [headView addSubview:lineView1];
   
    //添加按钮
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(28.5, 25, 30, 30)];
    [btn1 setBackgroundImage:[UIImage imageNamed:@"放大镜"] forState:(UIControlStateNormal)];
    [headView addSubview:btn1];
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(87, 25, 30, 30)];
    [btn2 setBackgroundImage:[UIImage imageNamed:@"下载"] forState:(UIControlStateNormal)];
    [btn2 addTarget:self action:@selector(downloadAction) forControlEvents:(UIControlEventTouchUpInside)];
    [headView addSubview:btn2];
    
    UIButton *btn3 = [[UIButton alloc]initWithFrame:CGRectMake(145.5, 25, 30, 30)];
    [btn3 setBackgroundImage:[UIImage imageNamed:@"点赞"] forState:(UIControlStateNormal)];
    
    [btn3 addTarget:self action:@selector(CollectionAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [headView addSubview:btn3];
    
    UIButton *btn4 = [[UIButton alloc]initWithFrame:CGRectMake(204, 25, 30, 30)];
    [btn4 setBackgroundImage:[UIImage imageNamed:@"聊天"] forState:(UIControlStateNormal)];
    [headView addSubview:btn4];
    
    //添加登录头像
    UIButton *headerImgView = [[UIButton alloc] initWithFrame:CGRectZero];
    
    headerImgView.frame = CGRectMake(20, 82, 70, 70);
    
   UIImage *image = [CK_MenuViewController imageWithName:[CK_MenuViewController getMenuViewController].name];
    
    [headerImgView setImage:image forState:UIControlStateNormal];
    [headerImgView addTarget:self action:@selector(LoginAction:) forControlEvents:UIControlEventTouchUpInside];
    //添加到父视图
    [headView addSubview:headerImgView];
    
    UIButton *loginButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 142, 10, 10)];
    loginButton.backgroundColor = [UIColor greenColor];
    loginButton.layer.cornerRadius = 5;
    loginButton.layer.masksToBounds = YES;
    [loginButton setTitle:@"登录" forState:(UIControlStateHighlighted)];
    [loginButton addTarget:self action:@selector(LoginAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [headView addSubview:loginButton];

    return headView;
}

- (void)downloadAction {
    DoenloadTableController *downloadC = [[DoenloadTableController alloc]init];
    UINavigationController *naVC = [[UINavigationController alloc]initWithRootViewController:downloadC];
    [self presentViewController:naVC animated:YES completion:nil];
    
}

// 收藏事件
- (void)CollectionAction:(UIButton *)btn {
    
    LWXCollectionController *collectionC = [[LWXCollectionController alloc] init];
    
    UINavigationController *naVC = [[UINavigationController alloc]initWithRootViewController:collectionC];
    
    [self presentViewController:naVC animated:YES completion:nil];

}

// 登录事件
- (void)LoginAction:(UIButton *)btn {
    
    UIStoryboard *longinStoryboar = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    
    UIViewController *loginVC = [longinStoryboar instantiateInitialViewController];
    
    //模态登陆页面
    [self presentViewController:loginVC animated:YES completion:nil];
    
}

// 图片切圆
+ (UIImage *)imageWithName:(NSString *)name {
    //加载原图片
    UIImage *oldImg = [UIImage imageNamed:name];
    //开启上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(oldImg.size.width, oldImg.size.height) , NO, 0.0);
    //获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //画边框 （大圆）
    CGFloat radius = oldImg.size.width * 0.5;
    CGContextAddArc(ctx, radius, radius, radius, 0, M_PI * 2, 2.0);
    CGContextFillPath(ctx);//画圆
    CGFloat smRadius = radius;
    CGContextAddArc(ctx, radius, radius, smRadius, 0, M_PI * 2, 0);
    CGContextClip(ctx); //裁剪
    //画图
    [oldImg drawInRect:CGRectMake(0, 0, oldImg.size.width, oldImg.size.height)];
    //取图
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    //结束上下文
    UIGraphicsEndImageContext();
    
    return newImg;
    
}

#pragma mark - viewForHeader


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 90;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kMenuLeftWidth, 90)];
   
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, 0, kMenuLeftWidth - 40, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [footerView addSubview:lineView];
    
    UIImageView *footerImgView = [[UIImageView alloc] initWithFrame:CGRectZero];
    
    footerImgView.frame = CGRectMake(20, 20, 50, 50);
    
    UIImage *image = [CK_MenuViewController imageWithName:[CK_MenuViewController getMenuViewController].name];
    
    footerImgView.image = image;
    //添加到父视图
    [footerView addSubview:footerImgView];
    
    UILabel *songLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 20, 130, 35)];
    
    songLabel.text = @"songName";
    songLabel.textAlignment = NSTextAlignmentLeft;
    songLabel.font = [UIFont systemFontOfSize:20];
    songLabel.textColor = [UIColor whiteColor];
    
    [footerView addSubview:songLabel];
    
    UILabel *singerLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 55, 130, 15)];
    
    singerLabel.text = @"singerName";
    singerLabel.textAlignment = NSTextAlignmentLeft;
    singerLabel.font = [UIFont systemFontOfSize:12];
    singerLabel.textColor = [UIColor whiteColor];
    
    [footerView addSubview:singerLabel];
    
    
    return footerView;

}


// 获取抽屉方法
+ (instancetype)getMenuViewController {
    return CK_menuVC;
}

// 展示左侧菜单
- (void)showLeftViewController {
    // 动画展开
    [self showLeftViewController:0.7];
}
- (void)showLeftViewController:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
    }];

}
// 关闭左侧菜单
- (void)hideLeftViewController {
    [self hideLeftViewController:0.7];
}
- (void)hideLeftViewController:(CGFloat)duration {
    // 动画关闭
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

#pragma mark MenuPanGesture

- (void)viewDidLoad {
    [super viewDidLoad];

    // 手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithPanGesture:)];
    [self.view addGestureRecognizer:pan];
    // Do any additional setup after loading the view.
}


// 静态变量保存初始状态
static CGPoint begin;
static CGAffineTransform transform;
- (void)panMenuWithPanGesture:(UIPanGestureRecognizer *)pan {
    // 位移量
    CGPoint translatePoint = CGPointZero;
    // 开始手势时的位置
    if (pan.state == UIGestureRecognizerStateBegan) {
        begin = [pan locationInView:self.view];
        transform = self.centerViewController.view.transform;
    }
    // 手势过程中的位置
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint end = [pan locationInView:self.view];
        
        translatePoint = CGPointMake(end.x - begin.x, 0);
    }
    // 手势结束时的位置
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        if ([pan velocityInView:self.view].x > 0) {
            // 动画设置动画时长
            [self showLeftViewController:0.13];
        }else {
            [self hideLeftViewController:0.13];
        }
        return;
    }
  
    // 手势过程中，对视图进行位移
    if((self.centerViewController.view.transform.tx >= 0 && translatePoint.x < 0) && self.centerViewController.view.transform.tx <= kMenuLeftWidth && translatePoint.x > 0) {
        self.centerViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        self.leftViewController.view.transform = CGAffineTransformTranslate(transform,translatePoint.x, 0);
        self.leftTableView.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
    }
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
